<script setup lang="ts">
import { deleteResourceCategory, getResourceCategoryList, udateOrAddResourceCategory } from '@/api/resource-category'
import type { ResourceCategoryData } from '@/api/resource-category'
import { useToggle } from '@vueuse/core';
import { useI18n } from 'vue-i18n'
import { timeFormatter } from '@/utils/dayjs'

// 国际化
const { t } = useI18n()

// Vueuse加载效果、危险提示
const [isLoading, toggleLoading] = useToggle(false);
// 弹窗
const [dialogVisible, toggleDialogVisible] = useToggle(false);

const dialogType = ref<0 | 1>(0); // 0新增 1编辑

// 编辑框表单初始化
const initialForm = {
    name: '',
    sort: 0,
}

const form = ref({ ...initialForm })

// 资源类别列表初始化
const resourceCategoryList = ref<ResourceCategoryData[]>([])

// 编辑逻辑
function hdlEdit(value: typeof initialForm) {
    dialogType.value = 1
    form.value = value
    toggleDialogVisible(true)
}

// 删除逻辑
async function hdlDelete(id: number) {
    await ElMessageBox.confirm('确认删除该资源类别？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).catch(() => {
        ElMessage.info('取消删除');
        return new Promise(() => { }); // pending状态
    })
    toggleLoading(true);

    // 调用接口函数
    const { data } = await deleteResourceCategory(id);
    if (data.code === '000000') {
        ElMessage.success('资源类别删除成功');
        fetchData();
    } else {
        ElMessage.error('资源类别删除失败');
        throw new Error('资源类别删除失败');
    }
    toggleLoading(false);
}

// 新增逻辑
function hdlAdd() {
    dialogType.value = 0
    form.value = { ...initialForm }
    toggleDialogVisible(true)
}

// 表单提交逻辑
async function hdlSubmit() {
    toggleLoading(true);
    if (dialogType.value === 0) {
        // 新增
        const { data } = await udateOrAddResourceCategory(form.value)
        if (data.code === '000000') {
            ElMessage.success(`资源类别添加成功`)
            fetchData();
        } else {
            ElMessage.error(`资源类别添加失败`)
            throw new Error('资源类别添加失败')
        }
        toggleDialogVisible(false);
    } else {
        // 编辑
        const { data } = await udateOrAddResourceCategory(form.value)
        if (data.code === '000000') {
            ElMessage.success(`资源更新成功`)
            fetchData();
        } else {
            ElMessage.error(`资源更新失败`)
            throw new Error('资源更新失败')
        }
        toggleDialogVisible(false);
    }
    toggleLoading(false);
}

// 获取资源类别列表
async function fetchData() {
    toggleLoading(true)
    const { data } = await getResourceCategoryList()
    if (data.code === '000000') {
        resourceCategoryList.value = data.data
    } else {
        ElMessage.error(t('resourceCategory.fetchError'))
        throw new Error(t('resourceCategory.fetchError'))
    }
    toggleLoading(false)
}

// 挂载渲染列表
onMounted(fetchData)  
</script>

<template>
    <div class="resource-category-index">
        <el-dialog v-model="dialogVisible" width="700" :title="dialogType === 0 ? '添加数据' : '编辑数据'">
            <el-form :model="form">
                <el-form-item label="类别名称">
                    <el-input v-model="form.name" autocomplete="off" style="width: 500px;" />
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="form.sort" autocomplete="off" style="width: 500px;" />
                </el-form-item>
            </el-form>
            <template #footer>
                <ElButton @click="toggleDialogVisible(false)" :loading="isLoading">取消</ElButton>
                <ElButton type="primary" @click="hdlSubmit" :loading="isLoading">确定</ElButton>
            </template>
        </el-dialog>
        <div>
            <ElButton size="large" @click="hdlAdd">{{ t('resourceCategory.addButton') }}</ElButton>
        </div>
        <el-divider>
            <el-icon><el-icon-star-filled /></el-icon>
        </el-divider>
        <div v-loading="isLoading">
            <ElTable :data="resourceCategoryList" border style="width: 100%;">
                <ElTableColumn type="index" label="序号" align="center" />
                <ElTableColumn prop="name" label="名称" align="center" />
                <ElTableColumn prop="createdTime" :formatter="timeFormatter" label="创建时间" align="center" />
                <ElTableColumn prop="sort" label="排序" align="center" />
                <ElTableColumn label="操作" align="center">
                    <template #default="scope">
                        <ElButton @click="hdlEdit(scope.row)">编辑</ElButton>
                        <ElButton type="danger" @click="hdlDelete(scope.row.id)">删除</ElButton>
                    </template>
                </ElTableColumn>
            </ElTable>
        </div>
    </div>
</template>

<style scoped lang="scss">
.resource-category-index {
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
    // background-color: rgb(255, 255, 255);
    padding: 0.5rem;
}
</style>
